package company

import (
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/logger"
	types2 "iot-base/auth/types"
	"strings"
)

func Add(c *gin.Context) {
	requestId := c.GetString("RequestId")
	resp := types2.NewResult(c)
	var req types2.ReqAddCompany
	err := c.ShouldBind(&req)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	compLogic := logic2.NewCompanyLogic()
	req.RoleId = 1 // todo 给管理员制定一个角色
	company, err := compLogic.Add(req)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	resp.Success(gin.H{"group_id": company.GroupId})
}

func List(c *gin.Context) {
	requestId := c.GetString("RequestId")
	resp := types2.NewResult(c)
	var req types2.BasePage
	err := c.ShouldBind(&req)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	compLogic := logic2.NewCompanyLogic()
	total, err := compLogic.FindCount()
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}

	list, err := compLogic.FindList(req.Page, req.Size)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	resp.Success(gin.H{"list": list, "total": total})
}

func Del(c *gin.Context) {
	requestId := c.GetString("RequestId")
	resp := types2.NewResult(c)
	var req types2.ReqId
	err := c.ShouldBind(&req)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	compLogic := logic2.NewCompanyLogic()
	_, err = compLogic.Del(req.ID)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		if strings.Contains(err.Error(), "users") {
			// 公司下挂有用户不能删除
			resp.ErrorCode(types2.DelRelationUser, "")
			return
		}
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	resp.Success(gin.H{})
}

func Update(c *gin.Context) {
	requestId := c.GetString("RequestId")
	resp := types2.NewResult(c)
	var req types2.ReqUpdateCompany
	err := c.ShouldBind(&req)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	compLogic := logic2.NewCompanyLogic()
	_, err = compLogic.Update(req)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	resp.Success(gin.H{})
}
